//
//  RadioGroup.swift
//  SimpleCal
//
//  Created by 杜晓祥 on 2021/10/21.
//

import Foundation

class RadioGroup<T: BaseView>: SimpleClickHandler {
    
    private var viewList = [T]()
    
    private var selectView:T?
    var btnChange: ((_ params: NSObject?)->())?
    
    var change:SimpleChangeHandler?
    
    
    func addSubview(view:T) {
        view.click = self         //统一点击事件处理
        view.singleButton = true
        if view.defaultSelect {   //默认选中项设置
            selectView?.setStyle(selectView?.defaultStyle)
            selectView?.defaultSelect = false
            selectView = view
            selectView?.setStyle(selectView?.mouseDownStyle)
        }
        viewList.append(view)
    }

    func getSubview(index:Int) -> T {
        return viewList[index]
    }
    
    func findAll() -> [T] {
        return viewList
    }
    
    func count() -> Int {
        return viewList.count
    }
    
    func onClick(_ params: NSObject?) {
        clean(defaultSelect: false)
        selectView = params as? T
        selectView?.selected = true
        selectView?.setStyle(selectView?.mouseDownStyle)
        change?.onChange(selectView)
        btnChange?(params)
    }
    
    /**
     清除选中项
     - parameter defaultSelect: 默认选中项是否起作用，false，清除所有选中项，true选中项改为默认选中项
     */
    func clean(defaultSelect:Bool) {
        for v in viewList {
            v.setStyle(v.defaultStyle)
            v.selected = false
            v.defaultSelect = false
            v.mouseExitHandler?()
//            if defaultSelect && v.defaultSelect {
//                v.setStyle(v.mouseDownStyle)
//                v.selected = true
//            }
        }
    }
    
    var isEnable:Bool = false {
        didSet {
            for t in viewList {
                t.isEnabled = isEnable
            }
        }
    }
}

